package com.ahdy.controller;

import com.ahdy.pojo.AsrResponse;
import com.ahdy.service.XunfeiAsrService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/asr")
@CrossOrigin
public class AsrController {

    @Autowired
    private XunfeiAsrService xunfeiAsrService;

    /**
     * 语音识别接口
     */
    @PostMapping("/recognize")
    public ResponseEntity<AsrResponse> recognize(@RequestParam("audio") MultipartFile audioFile) {
        log.info("收到语音识别请求 - 文件: {}, 大小: {} bytes",
                audioFile.getOriginalFilename(), audioFile.getSize());

        try {
            AsrResponse response = xunfeiAsrService.recognize(audioFile);

            if (response.isSuccess()) {
                log.info("语音识别成功 - 文本长度: {}, 耗时: {}ms",
                        response.getText().length(), response.getDuration());
                return ResponseEntity.ok(response);
            } else {
                log.warn("语音识别失败 - 错误: {}", response.getMessage());
                return ResponseEntity.badRequest().body(response);
            }
        } catch (Exception e) {
            log.error("语音识别异常", e);
            AsrResponse errorResponse = AsrResponse.error("服务器内部错误：" + e.getMessage());
            return ResponseEntity.internalServerError().body(errorResponse);
        }
    }

    /**
     * 检查服务状态
     */
    @GetMapping("/status")
    public ResponseEntity<Map<String, Object>> getStatus() {
        log.debug("检查语音识别服务状态");

        try {
            Map<String, Object> status = xunfeiAsrService.getServiceStatus();
            return ResponseEntity.ok(status);
        } catch (Exception e) {
            log.error("获取服务状态失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    /**
     * 健康检查接口
     */
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> health() {
        Map<String, Object> health = Map.of(
                "service", "Xunfei ASR",
                "status", xunfeiAsrService.isServiceAvailable() ? "UP" : "DOWN",
                "timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(health);
    }

    /**
     * 获取支持的音频格式
     */
    @GetMapping("/formats")
    public ResponseEntity<Map<String, Object>> getSupportedFormats() {
        Map<String, Object> formats = Map.of(
                "supportedFormats", new String[] {
                        ".wav", ".mp3", ".m4a", ".flac", ".aac", ".pcm"
                },
                "maxFileSize", "10MB",
                "description", "支持常见音频格式，建议使用16kHz采样率的音频文件");
        return ResponseEntity.ok(formats);
    }
}
